package com.zaofan.mobile.control;

import com.zaofan.bean.OpenBuilder;
import com.zaofan.mobile.bean.Account;
import com.zaofan.mobile.bean.HotelInfo;
import com.zaofan.service.AddressService;
import com.zaofan.service.HotelService;
import com.zaofan.service.OpenBuilderService;
import com.zaofan.service.UserFollowService;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.GsonUtils;
import com.zaofan.utils.HTTPClient;
import com.zaofan.utils.JsonUtils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2016/5/24.
 */
@Controller
@RequestMapping("/")
public class LoginController {


    private HotelService hotelService = new HotelService();;
    private OpenBuilderService mOpenBuilderService = new OpenBuilderService();
    private AddressService addressService = new AddressService();

    UserFollowService userFollowService = new UserFollowService();

    @RequestMapping("/wechat.do")
    public String WeChat(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

        String redirect_url = "http://m.52letsgo.cn/wechat.do?QRCodeId="+request.getParameter("QRCodeId");
        System.out.println("新微信进入---------------------------");
        String code = request.getParameter("code");
        if(StringUtils.isEmpty(code)){
            String http = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            String appid = "&appid=wxf946190506655c2d";
            String redirect_uri = "&redirect_uri=" +
                    URLEncoder.encode(redirect_url, "utf8");
            String response_type = "&response_type=code";
            String scope = "&scope=snsapi_base";
            String state = "&state=16516516156#wechat_redirect";
            return "redirect:"+http + appid + redirect_uri + response_type + scope + state;
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=wxf946190506655c2d"+
                "&secret=25f4e517eeea25ea18e75cab31cc3b8b" +
                "&grant_type=authorization_code" +
                "&code=" + code;
        String openid = "";
        String result = HTTPClient.postJson(url, "");

        if (StringUtils.isNoneEmpty(result)) {
            HashMap map = GsonUtils.fromJson(result, HashMap.class);
            openid = map.get("openid").toString();
        }
        String QRCodeId  = request.getParameter("QRCodeId");
        if(StringUtils.isNoneEmpty(QRCodeId)){
            Map<String, String> map = new HashMap<>();
            map.put("QRCodeId", QRCodeId);
            System.out.println("新微信QRCodeId---------------------------"+QRCodeId);
            HTTPClient.postMap("http://m.52letsgo.cn/m/QRCode/record/count", map);
            return "redirect:http://m.52letsgo.cn/fe/wechat_ZF?openid="+openid+"&QRCodeId="+QRCodeId;
        }


        System.out.println("新微信openid---------------------------"+openid);

        return "redirect:http://m.52letsgo.cn/fe/wechat_ZF?openid="+openid;
    }

    @RequestMapping("/hotel.do")
    public String hotel(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("新酒店进入---------------------------");
        String hotelNo = request.getParameter("hotelNo");
        String redirect_url = "http://m.52letsgo.cn/hotel.do?hotelNo="+hotelNo;

        String code = request.getParameter("code");
        if(StringUtils.isEmpty(code)){
            String http = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            String appid = "appid=wxf946190506655c2d";
            String redirect_uri = "&redirect_uri=" +
                    URLEncoder.encode(redirect_url, "utf8");
            String response_type = "&response_type=code";
            String scope = "&scope=snsapi_base";
            String state = "&state=16516516156#wechat_redirect";
            System.out.println("获取code:"+http + appid + redirect_uri + response_type + scope + state);
            return "redirect:"+http + appid + redirect_uri + response_type + scope + state;
        }
        System.out.println("回调成功---------------------------");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=wxf946190506655c2d"+
                "&secret=25f4e517eeea25ea18e75cab31cc3b8b" +
                "&grant_type=authorization_code" +
                "&code=" + code;
        String openid = "";
        String result = HTTPClient.postJson(url, "");

        if (StringUtils.isNoneEmpty(result)) {
            HashMap map = GsonUtils.fromJson(result, HashMap.class);
            openid = map.get("openid").toString();
        }

        OpenBuilder openBuilder = new OpenBuilder();
        if(hotelNo==null||"".equals(hotelNo)){
            JsonUtils.writeFailJson("酒店编号不能为空失败", response);
        }
        else {
            HotelInfo hotelInfo = hotelService.findOpenHotelByHotelNo(hotelNo);
            openBuilder = mOpenBuilderService.findById(hotelInfo.getAddressId());
        }
        System.out.println("酒店openId---------------------------"+openid);
        System.out.println("酒店编号---------------------------"+hotelNo);
        System.out.println("酒店信息---------------------------"+openBuilder);
        return "redirect:http://m.52letsgo.cn/fe/hotel_ZF/#/?openid="+openid+"&hotelNo="+hotelNo+"&address="+openBuilder.getBuilderName()+"-"+openBuilder.getAddress();
    }



    @RequestMapping("/login.do")
    public String index(HttpServletRequest request,HttpServletResponse response) throws IOException, InterruptedException {
        Account account = (Account) request.getSession().getAttribute("userinfo");
        String redirect_url = "http://m.52letsgo.cn/login.do";


        String code  =  request.getParameter("code");
        if(code == null || code.equals("")){
            String http = "https://open.weixin.qq.com/connect/oauth2/authorize?";
            String appid = "&appid=wxf946190506655c2d";

            String redirect_uri = "&redirect_uri=" +
                    URLEncoder.encode(redirect_url, "utf8");
            String response_type = "&response_type=code";
            String scope = "&scope=snsapi_base";
            String state = "&state=16516516156#wechat_redirect";
			return "redirect:"+http + appid + redirect_uri + response_type + scope + state;
        }
        System.out.println("--------code-------"+code+"----------");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=wxf946190506655c2d"+
                "&secret=25f4e517eeea25ea18e75cab31cc3b8b" +
                "&grant_type=authorization_code" +
                "&code=" + code;

        String openid = "";
//            String openid = "GonTest1010";
        String result = HTTPClient.postJson(url, "");
        if (StringUtils.isNoneEmpty(result)) {
            HashMap map = GsonUtils.fromJson(result, HashMap.class);
            openid = map.get("openid").toString();
        }
        request.getSession().removeAttribute("address");
        request.getSession().removeAttribute("isHotel");
        request.getSession().removeAttribute("area");
        request.getSession().removeAttribute("rechargeCityName");
        request.getSession().removeAttribute("rechargeCityId");
        request.getSession().removeAttribute("hotelBuilder");
        request.getSession().removeAttribute("hotelInfo");
        request.getSession().removeAttribute("userinfo");
        request.getSession().removeAttribute("openid");

        request.getSession().setAttribute("openid",openid);


        if (account != null){
            return "redirect:/home/beforelogin/index.do";
        }
        return "/login/index";
    }

    @RequestMapping("/beforelogin/forgetPwd.do")
    public String forgetPwd(HttpServletRequest request, ModelMap modelMap){
        modelMap.put("title","找回密码");
        return "/login/forgetPwd";
    }
    @RequestMapping("/beforelogin/modifyPwd.do")
    public String modifyPwd(HttpServletRequest request,String mobile, ModelMap modelMap){
        modelMap.put("mobile",mobile);
        modelMap.put("title","修改密码");
        return "/login/modifyPwd";
    }
    @RequestMapping("/logout.do")
    public String logout(HttpServletRequest request, ModelMap modelMap){
        Enumeration<String> names = request.getSession().getAttributeNames();
        while (names.hasMoreElements())
            request.getSession().removeAttribute(names.nextElement());
        return "/login/index";
    }

    @RequestMapping("/beforelogin/test.do")
    public void logout(HttpServletRequest request, HttpServletResponse response){
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());

        try {
            List<Map<String, Object>> productClasses = qr.query("select id,className as ABC from productclass"
                    , new MapListHandler());
            JsonUtils.writeSuccessJson("查询成功", productClasses, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }





}
